<template>
  <div class="model-list">
    <div class="page-header">
      <h2>数据模型管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索模型..."
          prefix-icon="el-icon-search"
          clearable
          style="width: 200px; margin-right: 10px;"
        />
        <el-button @click="refreshModels" :loading="refreshing" type="info">
          <el-icon><el-icon-refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="primary" @click="$router.push('/models/create')">
          <el-icon><el-icon-plus /></el-icon>
          创建模型
        </el-button>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <el-card v-if="loading && !error" class="loading-card">
      <div class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
    </el-card>
    
    <!-- 错误提示 -->
    <el-alert
      v-else-if="error"
      :title="error"
      type="error"
      show-icon
      :closable="false"
      style="margin-bottom: 20px;"
    >
      <template #default>
        <div class="error-actions">
          <el-button @click="refreshModels" type="primary" size="small">
            重试
          </el-button>
        </div>
      </template>
    </el-alert>
    
    <!-- 数据表格 -->
    <el-card v-else>
      <el-table 
        :data="filteredModels" 
        style="width: 100%" 
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="模型名称" />
        <el-table-column prop="displayName" label="显示名称" />
        <el-table-column label="字段数">
          <template #default="scope">
            {{ scope.row.fields ? scope.row.fields.length : 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="navigateToData(scope.row)"
            >
              查看数据
            </el-button>
            <el-button 
              size="small" 
              @click="$router.push(`/models/${scope.row.name}/edit`)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="confirmDelete(scope.row)"
              :loading="deletingId === scope.row.id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
        
        <!-- 空数据状态 -->
        <template #empty>
          <div class="empty-state">
            <el-icon class="empty-icon"><el-icon-document /></el-icon>
            <p>暂无数据模型</p>
            <el-button type="primary" @click="$router.push('/models/create')">
              创建第一个模型
            </el-button>
          </div>
        </template>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useModelStore } from '../../stores/model'
import { ElMessageBox, ElMessage } from 'element-plus'

const router = useRouter()
const modelStore = useModelStore()
const refreshing = ref(false)
const deletingId = ref(null)
const loadingTimeout = ref(null)
const error = computed(() => modelStore.error)

// 确保模型数据有效
const models = computed(() => {
  // 确保返回有效的数组，并且每个模型对象都有必要的属性
  return Array.isArray(modelStore.models) 
    ? modelStore.models.filter(model => model && model.id && model.name)
    : []
})

const loading = computed(() => modelStore.loading)

// 添加搜索功能
const searchQuery = ref('')

const filteredModels = computed(() => {
  if (!searchQuery.value) return models.value
  
  const query = searchQuery.value.toLowerCase()
  return models.value.filter(model => 
    model.name.toLowerCase().includes(query) || 
    model.displayName.toLowerCase().includes(query) ||
    model.description.toLowerCase().includes(query)
  )
})

// 简化错误处理和超时逻辑
async function loadModels(showMessage = false) {
  try {
    if (loadingTimeout.value) {
      clearTimeout(loadingTimeout.value)
    }
    
    loadingTimeout.value = setTimeout(() => {
      if (modelStore.loading) {
        modelStore.loading = false
        ElMessage.warning('请求超时，请重试')
      }
    }, 10000)
    
    await modelStore.fetchModels()
    
    if (showMessage) {
      ElMessage.success('加载成功')
    }
  } catch (err) {
    console.error('加载失败:', err)
    if (showMessage) {
      ElMessage.error('加载失败: ' + (err.message || '未知错误'))
    }
  } finally {
    if (loadingTimeout.value) {
      clearTimeout(loadingTimeout.value)
      loadingTimeout.value = null
    }
  }
}

// 使用简化的函数
function refreshModels() {
  refreshing.value = true
  loadModels(true).finally(() => {
    refreshing.value = false
  })
}

// 导航到数据页面
function navigateToData(model) {
  if (!model || !model.name) {
    ElMessage.error('模型名称无效')
    return
  }
  
  // 显示加载提示
  const loading = ElMessage({
    message: '正在加载数据页面...',
    type: 'info',
    duration: 0
  })
  
  // 导航到数据页面
  router.push(`/data/${model.name}`)
    .then(() => {
      // 导航成功后关闭提示
      loading.close()
    })
    .catch(err => {
      console.error('导航失败:', err)
      loading.close()
      ElMessage.error('导航失败: ' + (err.message || '未知错误'))
    })
}

// 确认删除模型
async function confirmDelete(model) {
  if (!model || !model.id) {
    ElMessage.error('无效的模型数据')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除模型 "${model.displayName || model.name}" 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    deletingId.value = model.id
    
    try {
      await modelStore.deleteModel(model.id)
      ElMessage.success('模型删除成功')
    } catch (err) {
      if (err.response?.status === 400) {
        // 显示友好的提示信息
        ElMessageBox.alert(
          '该模型中包含数据，请先清空表中数据后再尝试删除。',
          '无法删除模型',
          {
            confirmButtonText: '我知道了',
            type: 'warning'
          }
        )
      } else {
        ElMessage.error('删除失败，请稍后重试')
      }
    }
  } catch (err) {
    if (err !== 'cancel') {
      // 不显示技术错误信息，而是显示友好的提示
      ElMessage.warning('操作取消')
    }
  } finally {
    deletingId.value = null
  }
}

// 生命周期钩子
onMounted(async () => {
  try {
    // 设置加载超时 - 10秒后自动结束加载状态
    loadingTimeout.value = setTimeout(() => {
      if (modelStore.loading) {
        console.warn('加载模型超时')
        ElMessage.warning('加载模型列表超时，请刷新重试')
        // 强制结束加载状态
        modelStore.loading = false
      }
    }, 10000)
    
    console.log('开始加载模型列表')
    
    // 设置超时
    const fetchPromise = modelStore.fetchModels()
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('加载超时，请刷新重试')), 5000)
    })
    
    await Promise.race([fetchPromise, timeoutPromise])
    
    console.log('模型列表加载完成，数量:', modelStore.models.length)
    
    // 检查模型是否加载成功
    if (!Array.isArray(modelStore.models) || modelStore.models.length === 0) {
      console.warn('模型列表为空，尝试再次加载')
      await modelStore.fetchModels()
    }
  } catch (err) {
    console.error('加载模型列表失败:', err)
    // 错误已经在store中设置，会通过computed属性显示
    
    // 如果加载失败，尝试再次加载
    setTimeout(() => {
      if (Array.isArray(modelStore.models) && modelStore.models.length === 0) {
        console.log('自动重试加载模型列表')
        refreshModels()
      }
    }, 2000)
  } finally {
    // 清除超时
    if (loadingTimeout.value) {
      clearTimeout(loadingTimeout.value)
      loadingTimeout.value = null
    }
  }
})

// 组件卸载前清除超时
onBeforeUnmount(() => {
  if (loadingTimeout.value) {
    clearTimeout(loadingTimeout.value)
    loadingTimeout.value = null
  }
})
</script>

<style scoped>
.model-list {
  padding: 20px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.loading-card {
  margin-bottom: 20px;
}

.loading-container {
  padding: 20px 0;
}

.error-actions {
  margin-top: 10px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 20px;
  color: #dcdfe6;
}
</style> 